#include "sht3x_dis.h"
#include "x_nucleo_iks01a1.h"
#include "math.h"
#include "task.h"
#include "wdg.h"
#include "app.h"
#include "eeprom.h"

void sht3x_dis_begin(void)
{
  
    if(sht3x_dis_init() != SHT3X_DIS_OK)
        app_fault_handle(APP_SHT3X_DIS_BEGIN_ERROR);
}

void sht3x_dis_process(uint16_t* data)
{
     temp_humi_t* sht3x_dis_data = (void*)data;
     
     if(sht3x_dis_read_single_slot_command(&sht3x_dis_data->temperature, &sht3x_dis_data->humitity) != SHT3X_DIS_OK)
         app_fault_handle(APP_SHT3X_DIS_READ_ERROR);    
}

SHT3X_DIS_StatusTypeDef sht3x_dis_init(void)
{
    if(SHT3X_DIS_IO_Init() != SHT3X_DIS_OK)
         return SHT3X_DIS_ERROR;
 
    return SHT3X_DIS_OK;
}

#ifdef SHT3X_CRC
static uint8_t SHT3X_CalcCrc(uint8_t data[], uint8_t nbrOfBytes){

    uint8_t bit;        // bit mask
    uint8_t crc = 0xFF; // calculated checksum
    uint8_t byteCtr;    // byte counter
  
    /* calculates 8-Bit checksum with given polynomial*/
    for(byteCtr = 0; byteCtr < nbrOfBytes; byteCtr++)
    {
      crc ^= (data[byteCtr]);
      for(bit = 8; bit > 0; --bit)
      {
        if(crc & 0x80) crc = (crc << 1) ^ POLYNOMIAL;
        else           crc = (crc << 1);
      }
    }
	
	   return crc;
}
#endif

SHT3X_DIS_StatusTypeDef sht3x_dis_read_single_slot_command(uint16_t* raw_temp, uint16_t* raw_hum)
{
    uint8_t tmp1[6] = {CMD_SINGLE_SLOT_REPEAT_HIGH_CLK_EN_LSB, 0x00, 0x00, 0x00, 0x00, 0x00};
    
//    __set_PRIMASK(255);
    SHT3X_DIS_IO_Write(tmp1, SHT3X_DIS_ADDRESS, CMD_SINGLE_SLOT_REPEAT_CLK_EN_MSB, 1);
//    __set_PRIMASK(0);
    HAL_Delay(15);
//    __set_PRIMASK(255);
    SHT3X_DIS_IO_Read(tmp1, SHT3X_DIS_ADDRESS, 0x00, 6, 0x00);
//    __set_PRIMASK(0);
    HAL_Delay(5);
#ifdef SHT3X_CRC
    uint8_t crc = 0, crc_1 = 0;
    /*check temperature crc*/
    crc = tmp1[2];
    crc_1 = SHT3X_CalcCrc(tmp1, 2);
    if(crc != crc_1)
        return SHT3X_DIS_ERROR;
    
    /*check humitity crc*/
    crc = tmp1[5];
    crc_1 = SHT3X_CalcCrc(&tmp1[3], 2);
    if(crc != crc_1)
        return SHT3X_DIS_ERROR;
#endif    
    /*tempeture value*/
    *raw_temp = ((uint16_t)tmp1[0] << 8) + tmp1[1];
    /*humitity value*/
    *raw_hum = ((uint16_t)tmp1[3] << 8) + tmp1[4];
    
    return SHT3X_DIS_OK;
}

